<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  NDataTable,
  type DataTableColumns,
  type UploadFileInfo,
  NSelect,
  NPagination
} from 'naive-ui'
import { h, onMounted, reactive, ref, inject, computed } from 'vue'
import type { IdentifyInfoModel, IdentifySubItemModel } from '@/api/batch'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import { useRoute, useRouter } from 'vue-router'
import FileList from '@/components/FileList.vue'

const props = defineProps<{
  identifyTypeCode: string
}>()

const route = useRoute()
const router = useRouter()
const isTF = ref(true)
const routeIdentifyId = route.query.identifyId as string | undefined
const process = inject('process') as (identifyId?: number) => Promise<void>

const identifyList = ref<IdentifyInfoModel[]>([])
const queryIdentifyList = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel[]>>({
      module: 'batch',
      api: 'identifyList',
      override: {
        params: {
          batchId: route.params.id,
          identifyTypeCode: props.identifyTypeCode
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    identifyList.value = res.data
    identifyList.value.forEach((e) => {
      if (!e.identifyTime) return
      e.identifyTime = e.identifyTime.split(' ')[0]
    })
    identifyList.value.forEach(async (e) => {
      e._files = await queryFileList(e.fileIds)
    })
    if (routeIdentifyId) handleUpdateIdentityId(Number(routeIdentifyId))
    if (res.data.length > 0) {
      handleUpdateIdentityId(res.data[0].id)
    } else {
      process()
    }
  } catch (error) {
    console.error(error)
  }
}

const identifyId = ref<number | null>(null)
const attachments = ref({} as any)
const identifyInfo = ref({} as IdentifyInfoModel)
const identifySumItemTableData = ref<IdentifySubItemModel[]>([])
const inventoryTableData = ref<IdentifySubItemModel[]>([])

const identifySumItemLoading = ref(false)
const inventoryLoading = ref(false)

const sumItemPaginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    sumItemPaginationReactive.page = page
    queryIdentifySumItemTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    sumItemPaginationReactive.pageSize = pageSize
    sumItemPaginationReactive.page = 1
    queryIdentifySumItemTableData()
  }
})
const inventoryPaginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    inventoryPaginationReactive.page = page
    queryInventoryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    inventoryPaginationReactive.pageSize = pageSize
    inventoryPaginationReactive.page = 1
    queryInventoryTableData()
  }
})

const columns: DataTableColumns<IdentifySubItemModel> = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (_, index) =>
      sumItemPaginationReactive.pageSize * (sumItemPaginationReactive.page - 1) + index + 1
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '征集品真伪',
    key: 'authenticity',
    render(e) {
      if (!e.authenticity) return '/'
      return e.authenticity === '0' ? '真' : e.authenticity === '1' ? '伪' : '无法确定'
    }
  },
  {
    title: '意见',
    key: 'opinion'
  }
]

// @ts-ignore
const listColumns = computed<DataTableColumns<IdentifySubItemModel>>(() => {
  return [
    {
      title: '序号',
      key: 'index',
      width: 80,
      align: 'center',
      // @ts-ignore
      render: (_, index) =>
        inventoryPaginationReactive.pageSize * (inventoryPaginationReactive.page - 1) + index + 1
    },
    {
      title: '征集品编码',
      key: 'subItemCode'
    },
    {
      title: '征集品名称',
      key: 'itemName'
    },
    {
      title: '类型',
      key: 'itemType'
    },
    {
      title: '价格区间（元）',
      key: 'identifyValue'
    },
    {
      title: '接收时间',
      key: 'receiveTime'
    },
    {
      title: '移交人',
      key: 'transferUser'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      // @ts-ignore
      render(e) {
        return h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            quaternary: true,
            onClick: () => {
              router.push({
                name: 'detailBatchItem',
                params: {
                  id: route.params.id,
                  itemId: e.itemId
                },
                query: {
                  type: 'r',
                  redirect: route.fullPath,
                  fromRegisteredDetail: 'true',
                  identifyId: identifyId.value,
                  subItemId: e.id,
                  isTF: isTF.value.toString()
                }
              })
            }
          },
          {
            default: () => '详情'
          }
        )
      }
    }
  ].filter((e) => (isTF.value ? e.key !== 'identifyValue' : true))
})

const queryIdentifySumItemTableData = async () => {
  try {
    identifySumItemLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: identifyId.value,
          limit: sumItemPaginationReactive.pageSize,
          page: sumItemPaginationReactive.page
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    identifySumItemTableData.value = res.data.list
    sumItemPaginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.error(error)
  } finally {
    identifySumItemLoading.value = false
  }
}

const queryInventoryTableData = async () => {
  try {
    inventoryLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: identifyId.value,
          limit: inventoryPaginationReactive.pageSize,
          page: inventoryPaginationReactive.page
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    inventoryTableData.value = res.data.list
    inventoryPaginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.error(error)
  } finally {
    inventoryLoading.value = false
  }
}

const queryAttachments = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'batch',
      api: 'identifyRegisterDetail',
      override: {
        params: {
          identifyId: identifyId.value
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    attachments.value = res.data
    filesData.forEach((e) => {
      const files = res.data[e.key]
      if (!files) return (e.files = [])
      e.files = files.map((e: any) => ({
        id: e.id,
        name: e.name,
        status: 'finished',
        url: e.path,
        type: e.type
      }))
    })
  } catch (error) {
    console.error(error)
  }
}

const handleUpdateIdentityId = (id: number) => {
  process(id)
  identifyId.value = id
  queryIdentifySumItemTableData()
  queryInventoryTableData()
  queryAttachments()

  const identify = identifyList.value.find((e) => e.id === id)
  if (identify) {
    identifyInfo.value = identify
    isTF.value = identify.identifyTypeCode === 'A3101'
  }
}

const queryFileList = async (filesIds: string): Promise<UploadFileInfo[]> => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    return res.data.map((e) => ({
      id: e.id,
      name: e.name,
      status: 'finished',
      url: e.path,
      type: e.type
    }))
  } catch (error) {
    return []
  }
}

const filesData = reactive<
  {
    label: string
    key: string
    files: UploadFileInfo[]
  }[]
>([
  {
    label: '鉴定方案',
    key: 'planFiles',
    files: []
  },
  {
    label: '专家鉴定意见',
    key: 'expertFiles',
    files: []
  },
  {
    label: '汇总鉴定意见',
    key: 'summaryResultFiles',
    files: []
  },
  {
    label: '会议汇报材料',
    key: 'meetingResultFiles',
    files: []
  },
  {
    label: '会议纪要材料',
    key: 'meetingMinutesFiles',
    files: []
  },
  {
    label: '合同和发票材料',
    key: 'contractFiles',
    files: []
  },
  {
    label: '视频材料',
    key: 'videoFiles',
    files: []
  },
  {
    label: '音频材料',
    key: 'audioFiles',
    files: []
  },
  {
    label: '其他材料',
    key: 'otherFiles',
    files: []
  },
  {
    label: '价格结果材料',
    key: 'priceFiles',
    files: []
  },
  {
    label: '谈判会材料',
    key: 'talkFiles',
    files: []
  }
  // {
  //   label: '补充登记材料',
  //   key: 'supplementFiles',
  //   files: []
  // }
])

onMounted(() => queryIdentifyList())
</script>

<template>
  <DetailFormProvider>
    <div class="bd-title">鉴定信息</div>
    <NForm
      disabled
      label-placement="left"
      label-width="100rem"
      class="bd-card grid grid-3"
    >
      <NFormItem label="鉴定编号：">
        <NSelect
          v-if="!routeIdentifyId"
          :options="identifyList"
          :disabled="false"
          placeholder="/"
          value-field="id"
          label-field="identifyCode"
          :value="identifyId"
          @update:value="handleUpdateIdentityId"
          class="jdbh-select"
        />
        <NInput
          v-else
          placeholder="/"
          :value="identifyInfo.identifyCode"
        />
      </NFormItem>
      <NFormItem label="鉴定名称：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyName"
        />
      </NFormItem>
      <NFormItem label="鉴定日期：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyTime"
        />
      </NFormItem>
      <NFormItem label="鉴定地点：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyAddress"
        />
      </NFormItem>
      <NFormItem label="鉴定类型：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyType"
        />
      </NFormItem>
      <NFormItem label="鉴定专家：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyExperts?.join('，')"
        />
      </NFormItem>
      <NFormItem label="描述：">
        <NInput
          placeholder="/"
          type="textarea"
          :value="identifyInfo.identifyDescription"
          rows="1"
        />
      </NFormItem>
      <NFormItem label="附件：">
        <FileList
          v-if="identifyInfo.fileIds"
          :file-list="identifyInfo._files"
        />
      </NFormItem>
    </NForm>

    <div class="br"></div>

    <template v-if="isTF">
      <div class="bd-title">汇总结果</div>
      <NForm
        disabled
        label-placement="left"
        label-width="120rem"
        :show-feedback="false"
        inline
        class="bd-card grid grid-3"
      >
        <NFormItem label="鉴定汇总意见：">
          <NInput
            placeholder="/"
            :value="attachments.totalOpinion"
          />
        </NFormItem>
        <NFormItem label="备注：">
          <NInput
            placeholder="/"
            type="textarea"
            rows="1"
            :value="attachments.remark"
          />
        </NFormItem>
      </NForm>
      <NDataTable
        :loading="identifySumItemLoading"
        :data="identifySumItemTableData"
        :columns="columns"
        height="200rem"
        class="bd-card"
      />
      <NPagination
        class="bd-card"
        style="padding-top: 0"
        show-size-picker
        show-quick-jumper
        :page-sizes="sumItemPaginationReactive.pageSizes"
        :item-count="sumItemPaginationReactive.itemCount"
        :page="sumItemPaginationReactive.page"
        :page-size="sumItemPaginationReactive.pageSize"
        @update:page="sumItemPaginationReactive.onChange"
        @update:page-size="sumItemPaginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ sumItemPaginationReactive.itemCount }}条</span>
        </template>
      </NPagination>

      <div class="br"></div>
    </template>

    <div class="bd-title">鉴定清单</div>
    <NDataTable
      :loading="inventoryLoading"
      :data="inventoryTableData"
      :columns="listColumns"
      height="200rem"
      class="bd-card"
    />
    <NPagination
      class="bd-card"
      style="padding-top: 0"
      show-size-picker
      show-quick-jumper
      :page-sizes="inventoryPaginationReactive.pageSizes"
      :item-count="inventoryPaginationReactive.itemCount"
      :page="inventoryPaginationReactive.page"
      :page-size="inventoryPaginationReactive.pageSize"
      @update:page="inventoryPaginationReactive.onChange"
      @update:page-size="inventoryPaginationReactive.onUpdatePageSize"
    >
      <template #suffix>页</template>
    </NPagination>

    <div class="br"></div>

    <div class="bd-title">附件</div>
    <NForm
      class="bd-card attachment-grid"
      require-mark-placement="left"
      label-placement="left"
      disabled
    >
      <div
        v-for="item in filesData"
        :key="item.key"
        class="attachment"
      >
        <div class="attachment-title">{{ item.label }}</div>
        <NFormItem label="附件：">
          <FileList :file-list="item.files" />
        </NFormItem>
      </div>
    </NForm>
  </DetailFormProvider>
</template>

<style scoped lang="scss">
.jdbh-select {
  position: relative;

  &::after {
    content: '可点击下拉查看其余鉴定信息';
    position: absolute;
    left: 0;
    font-size: 12rem;
    bottom: 0;
    translate: 0 100%;
    color: red;
  }
}

.br {
  position: relative;
  width: 100%;
  padding: 30rem 0;

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 50%;
    left: 0;
    border-top: 1px dotted #bc9e70;
    transform: translateY(-50%);
  }
}

.bd-card {
  padding: 20rem;
  background-color: #e1e1e1;
}

.n-form.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0 60rem;

  &.grid-3 {
    grid-template-columns: repeat(3, 1fr);
  }
}

.n-form.attachment-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10rem 15rem;
  padding: 20rem 30rem;

  .attachment {
    &-title {
      margin-bottom: 0.5em;
      font-weight: 600;
      font-size: 16rem;
    }

    .n-form-item {
      margin-left: 2em;
    }
  }
}

.bd-title {
  font-size: 26rem;
  margin-bottom: 30rem;
  color: #048c5e;
  line-height: 1;
}

.bd-flow {
  display: flex;
  align-items: center;
  padding: 20rem 20rem 30rem;
  gap: 0 1.5em;

  .step {
    padding: 10rem 15rem;
    background-color: #e1e1e1;

    &.finished {
      color: #fff;
      background-color: #6cb187;
    }
  }
}

.batch-detail-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 0 16rem;
}
</style>
